﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Xml.Linq;
using System.ComponentModel;
using System.Web.Script.Services;
using Silverlight.DataSetConnector;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.Objective;
using Jumpton.SFA.Server.BusinessRule.CallRoute;
using Jumpton.SFA.Server.Entity;
using Jumpton.Data;
using Jumpton.Persistent;
using System.ServiceModel;


    /// <summary>
    ///MyService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。 
    [System.Web.Script.Services.ScriptService]

    public class RoutePlanService : System.Web.Services.WebService
    {

        // MyStateManager myStateManager;
        StateManager myStateManager;

        public RoutePlanService()
        {

            //如果使用设计的组件，请取消注释以下行 
            //InitializeComponent(); 
            myStateManager = new StateManager();

        }

        /// <summary>
        /// 获取客户类型
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        [XmlSerializerFormat]
        public List<string> GetCustomerType()
        {
            int i = 0;
            string LogContent = "";
            try
            {
                DataTable dt = new DictionaryItemsManager().GetItemList(DictionaryEnum.CustomerClass, myStateManager.DomainID).BillDataTable;
                List<string> list = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    list.Add(ConvertData(dr["Name"].ToString())); i++;
                }
                LogContent += "获取客户类型:";
                if (list != null)
                    LogContent += "成功获取" + list.Count + "条客户类型。";
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
            Jumpton.SFA.Server.BusinessRule.System.LogType.USER_DOWNLOAD, myStateManager.Person_Name,
            myStateManager.UserID, LogContent);

                return list;


            }
            catch (Exception ex)
            {
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
           Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION,myStateManager.Person_Name,
          myStateManager.UserID, "获取客户类型 - 异常:" + ex.Message);
                throw ex;
            }
        }

        private string ConvertData(string p)
        {
            return p.Replace("|", "&brvbar");
        }

        /// <summary>
        /// 获取业代关联客户
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        [XmlSerializerFormat]
        public List<string> SelectUserCustomer()
        {
            //StateManager myState = new StateManager();
            //int.Parse(myState.UserID.ToString())
            string LogContent = "";
            try
            {
                DataTable dt = CustomerRouteManager.SelectUserCustomer(int.Parse(myStateManager.UserID.ToString()), myStateManager.DomainID, myStateManager.OrgID).Tables[0];
                List<string> list = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    string s = this.ConvertData(dr["ID"].ToString()) + '|' + this.ConvertData(dr["Name"].ToString());
                    list.Add(s);
                }

                LogContent += "获取业代关联客户:";
                if (list != null)
                    LogContent += "成功获取" + list.Count + "条业代关联客户。";
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
            Jumpton.SFA.Server.BusinessRule.System.LogType.USER_DOWNLOAD, myStateManager.Person_Name,
            myStateManager.UserID, LogContent);
                return list;
            }
            catch (Exception ex)
            {
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
          Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, myStateManager.Person_Name,
         myStateManager.UserID, "获取业代关联客户 - 异常:" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 获取客户级别
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        [XmlSerializerFormat]
        public List<string> GetStoreLevel()
        {
            string LogContent = "";
            try
            {
                DataTable dt = new DictionaryItemsManager().GetItemList(DictionaryEnum.Store_Level, myStateManager.DomainID).BillDataTable;
                List<string> list = new List<string>();

                foreach (DataRow dr in dt.Rows)
                {
                    if(!list.Contains(dr["Name"].ToString()))
                        list.Add(ConvertData(dr["Name"].ToString()));
                }

                LogContent += "获取客户级别:";
                if (list != null)
                    LogContent += "成功获取" + list.Count + "条客户级别。";
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
            Jumpton.SFA.Server.BusinessRule.System.LogType.USER_DOWNLOAD, myStateManager.Person_Name,
            myStateManager.UserID, LogContent);
                return list;
            }
            catch (Exception ex)
            {
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
          Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, myStateManager.Person_Name,
         myStateManager.UserID, "获取客户级别 - 异常:" + ex.Message);
                throw ex;
            }
        }

         /// <summary>
         /// 获取拜访计划
         /// </summary>
         /// <param name="date"></param>
         /// <param name="userID"></param>
         /// <returns></returns>
        [WebMethod]
        [XmlSerializerFormat]
        public String GetVisitPlan(DateTime date, decimal userID)
        {
            string LogContent = "";
            try
            {
                DataSet dataSet = new VisitManager().GetVisitPlan(date, userID);
                 // Serialize ADO.Net DataSet into xml for sending it to Silverlight front-end

                LogContent += "获取拜访计划:";
                if (dataSet != null)
                    LogContent += "成功获取" + dataSet.Tables[0].Rows.Count + "条拜访计划。";
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
            Jumpton.SFA.Server.BusinessRule.System.LogType.USER_DOWNLOAD, myStateManager.Person_Name,
            myStateManager.UserID, LogContent);
                return Connector.ToXml(dataSet, false);
            }
            catch (Exception ex)
            {
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
          Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, myStateManager.Person_Name,
         myStateManager.UserID, "获取拜访计划 - 异常:" + ex.Message);
                 throw ex;
            }
            
        }


        /// <summary>
        /// 保存拜访计划
        /// </summary>
        /// <param name="data"></param>
        /// <param name="UserID"></param>
        /// <returns></returns>
        [WebMethod]
        [XmlSerializerFormat]
        public bool SaveVisitPlan(String data, decimal UserID)
        {
            DataSet ds = Connector.FromXml(data);
            string LogContent = "";
            try
            {
                var vpMan = new VisitManager();
                bool back = true;
                decimal psnID = myStateManager.PersonID;
                String Route1Customers = null, Route2Customers = null, Route3Customers = null,
                    Route4Customers = null, Route5Customers = null, Route6Customers = null, Route7Customers = null, TempRoute8Customers = null, TempRoute9Customers = null, TempRoute10Customers = null, TempRoute11Customers = null, TempRoute12Customers = null, TempRoute13Customers = null, TempRoute14Customers = null, TempRoute15Customers = null, TempRoute16Customers = null, TempRoute17Customers = null;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (row["Route1"] != DBNull.Value && (Boolean)row["Route1"])
                    {
                        Route1Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route2"] != DBNull.Value && (Boolean)row["Route2"])
                    {
                        Route2Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route3"] != DBNull.Value && (Boolean)row["Route3"])
                    {
                        Route3Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route4"] != DBNull.Value && (Boolean)row["Route4"])
                    {
                        Route4Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route5"] != DBNull.Value && (Boolean)row["Route5"])
                    {
                        Route5Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route6"] != DBNull.Value && (Boolean)row["Route6"])
                    {
                        Route6Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["Route7"] != DBNull.Value && (Boolean)row["Route7"])
                    {
                        Route7Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE8"] != DBNull.Value && (Boolean)row["TEMPROUTE8"])
                    {
                        TempRoute8Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE9"] != DBNull.Value && (Boolean)row["TEMPROUTE9"])
                    {
                        TempRoute9Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE10"] != DBNull.Value && (Boolean)row["TEMPROUTE10"])
                    {
                        TempRoute10Customers += row["Customer_ID"].ToString() + ",";
                    }if (row["TEMPROUTE11"] != DBNull.Value && (Boolean)row["TEMPROUTE11"])
                    {
                        TempRoute11Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE12"] != DBNull.Value && (Boolean)row["TEMPROUTE12"])
                    {
                        TempRoute12Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE13"] != DBNull.Value && (Boolean)row["TEMPROUTE13"])
                    {
                        TempRoute13Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE14"] != DBNull.Value && (Boolean)row["TEMPROUTE14"])
                    {
                        TempRoute14Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE15"] != DBNull.Value && (Boolean)row["TEMPROUTE15"])
                    {
                        TempRoute15Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE16"] != DBNull.Value && (Boolean)row["TEMPROUTE16"])
                    {
                        TempRoute16Customers += row["Customer_ID"].ToString() + ",";
                    }
                    if (row["TEMPROUTE17"] != DBNull.Value && (Boolean)row["TEMPROUTE17"])
                    {
                        TempRoute17Customers += row["Customer_ID"].ToString() + ",";
                    }
                }

                if (!String.IsNullOrEmpty(Route1Customers))
                    Route1Customers = Route1Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route2Customers))
                    Route2Customers = Route2Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route3Customers))
                    Route3Customers = Route3Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route4Customers))
                    Route4Customers = Route4Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route5Customers))
                    Route5Customers = Route5Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route6Customers))
                    Route6Customers = Route6Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(Route7Customers))
                    Route7Customers = Route7Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute8Customers))
                    TempRoute8Customers = TempRoute8Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute9Customers))
                    TempRoute9Customers = TempRoute9Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute10Customers))
                    TempRoute10Customers = TempRoute10Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute11Customers))
                    TempRoute11Customers = TempRoute11Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute12Customers))
                    TempRoute12Customers = TempRoute12Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute13Customers))
                    TempRoute13Customers = TempRoute13Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute14Customers))
                    TempRoute14Customers = TempRoute14Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute15Customers))
                    TempRoute15Customers = TempRoute15Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute16Customers))
                    TempRoute16Customers = TempRoute16Customers.TrimEnd(',');
                if (!String.IsNullOrEmpty(TempRoute17Customers))
                    TempRoute17Customers = TempRoute17Customers.TrimEnd(',');

                Boolean Successful = false;
                foreach (DataRow row in ds.Tables[1].Rows)
                {
                    String ROUTE_FORCE = null;
                    String ACTIVE = null;
                    String VALID_DATE = null;
                    String ROUTE_NUMBER = null;
                    if (row["ROUTE_NUMBER"] != DBNull.Value)
                    {
                        ROUTE_NUMBER = row["ROUTE_NUMBER"].ToString();
                    }
                    if (row["ROUTE_FORCE"] != DBNull.Value)
                    {
                        ROUTE_FORCE = row["ROUTE_FORCE"].ToString();
                    }
                    if (row["ACTIVE"] != DBNull.Value)
                    {
                        ACTIVE = row["ACTIVE"].ToString();
                    }
                    if (row["VALID_DATE"] != DBNull.Value)
                    {
                        try
                        {
                            VALID_DATE = row["VALID_DATE"].ToString();
                            VALID_DATE = BusinessLogic.GetDateTimeDecimal(DateTime.Parse(VALID_DATE)).ToString();
                        }
                        catch { }
                    }
                    String RouteCustomers = null;
                    int number = int.Parse(ROUTE_NUMBER);
                    switch (number)
                    {
                        case 1:
                            {
                                RouteCustomers = Route1Customers;
                                break;
                            }
                        case 2:
                            {
                                RouteCustomers = Route2Customers;
                                break;
                            }
                        case 3:
                            {
                                RouteCustomers = Route3Customers;
                                break;
                            }
                        case 4:
                            {
                                RouteCustomers = Route4Customers;
                                break;
                            }
                        case 5:
                            {
                                RouteCustomers = Route5Customers;
                                break;
                            }
                        case 6:
                            {
                                RouteCustomers = Route6Customers;
                                break;
                            }
                        case 7:
                            {
                                RouteCustomers = Route7Customers;
                                break;
                            }
                        case 8:
                            {
                                RouteCustomers = TempRoute8Customers;
                                break;
                            }
                        case 9:
                            {
                                RouteCustomers = TempRoute9Customers;
                                break;
                            }
                        case 10:
                            {
                                RouteCustomers = TempRoute10Customers;
                                break;
                            }
                        case 11:
                            {
                                RouteCustomers = TempRoute11Customers;
                                break;
                            }
                        case 12:
                            {
                                RouteCustomers = TempRoute12Customers;
                                break;
                            }
                        case 13:
                            {
                                RouteCustomers = TempRoute13Customers;
                                break;
                            }
                        case 14:
                            {
                                RouteCustomers = TempRoute14Customers;
                                break;
                            }
                        case 15:
                            {
                                RouteCustomers = TempRoute15Customers;
                                break;
                            }
                        case 16:
                            {
                                RouteCustomers = TempRoute16Customers;
                                break;
                            }
                        case 17:
                            {
                                RouteCustomers = TempRoute17Customers;
                                break;
                            }
                    }
                    Successful = vpMan.UpdateRouteCustomers(UserID, ROUTE_FORCE.ToLower().Equals("false") ? 0:1, RouteCustomers,number , VALID_DATE, true);
                }

                LogContent += "保存拜访计划:";
                if (Successful)
                    LogContent += "成功保存拜访计划。";
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
            Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change, myStateManager.Person_Name,
            myStateManager.UserID, LogContent);
                return back;
            }
            catch (Exception ex)
            {
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
         Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, myStateManager.Person_Name,
        myStateManager.UserID, "保存拜访计划 - 异常:" + ex.Message);
                throw ex;
            }
            return false;
        }


     

        //[WebMethod]
        //[XmlSerializerFormat]
        //public List<string> GetPlanType()
        //{
        //    try
        //    {
        //        //name='业务员月度计划目标' and type=1
        //        string name = "业务员月度计划目标";
        //        int type = 1;
        //        ObjectiveManager_Yibai ory = new ObjectiveManager_Yibai();
        //        DataTable dt = ory.GetObjectiveDetailList(int.Parse(ory.LoadObjectiveByName(name, type, myStateManager.DomainID).ObjID.ToString())).BillDataTable;
        //        List<string> list = new List<string>();
        //        foreach (DataRow dr in dt.Rows)
        //        {
        //            string s = dr["objID"].ToString() + '|' + this.ConvertData(dr["Name"].ToString());
        //            list.Add(s);
        //        }

        //        return list;
        //    }
        //    catch (Exception ex)
        //    {

        //        throw ex;
        //    }
        //}

        //[WebMethod]
        //[XmlSerializerFormat]
        //public List<string> GetObjectiveDetail(decimal userID, string month)
        //{
        //    List<string> list = new List<string>();

        //    DataTable dt = new ObjectiveManager_Yibai().GetObjectiveDetailByMonthByUser(userID, myStateManager.DomainID, month);

        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        System.Text.StringBuilder str = new System.Text.StringBuilder();
        //        foreach (object x in dr.ItemArray)
        //        {
        //            str.Append(this.ConvertData(x.ToString()) + '|');
        //        }

        //        list.Add(str.ToString().Substring(0, str.Length - 1));
        //    }

        //    return list;
        //}

        //[WebMethod]
        //[XmlSerializerFormat]
        //public bool UpdateObjective(List<string> list)
        //{
        //    ObjectiveManager_Yibai omy = new ObjectiveManager_Yibai();
        //    bool back = true;
        //    foreach (string s in list)
        //    {
        //        string[] value = s.Split('|');

        //        Objective_Detail_Yibai od = omy.LoadYibaiDetail(int.Parse(value[0]));
        //        if (od != null)
        //        {
        //            od.ObjectiveData = decimal.Parse(value[1]);
        //            od.LAST_UPDATE_TIME = DateTime.Now;
        //        }
        //        if (!omy.SaveDetial(od))
        //        {
        //            back = false;
        //            break;
        //        }
        //    }

        //    return back;
        //}

        ///// <summary>
        ///// PDA省级经理获取下属订单
        ///// </summary>
        ///// <param name="orgid"></param>
        ///// <returns></returns>
        //[WebMethod]
        //[XmlSerializerFormat]
        //public byte[] GetEmployeeOrder(int orgid, string begin, string end)
        //{
        //    DataSet ds = eBest.mySales.Server.BusinessRule.OrderHeaderManager.SearchEmployeeOrders(orgid, begin, end);

        //    return Zip.Compress(ds.Tables[0].Copy());
        //}

        //[WebMethod]
        //[XmlSerializerFormat]
        //public byte[] GetEmployeePlan(int orgid, string begin, string end, string name)
        //{
        //    DataSet ds = eBest.mySales.Server.BusinessRule.CallRoute.VisitPlanManager.SearchEmployeePlans(orgid, begin,end, name);

        //    return Zip.Compress(ds.Tables[0].Copy());
        //}
    }


